<script setup lang="ts">
// 患病时间
import type { PartialConsultInfo } from '@/types/consult'
import type {
  UploaderAfterRead,
  UploaderBeforeRead,
  UploaderFileListItem
} from 'vant/lib/uploader/types'
import { computed, onMounted, ref } from 'vue'
import { uploadImageAPI } from '@/services/consult'
import { showConfirmDialog, showFailToast, showToast } from 'vant'
import { useConsultStore } from '@/stores'
import { useRouter } from 'vue-router'
import { timeOptions, illnessedOptions, imageTypes } from '@/common'
// 当前页面表单数据
const formData = ref<PartialConsultInfo>({
  illnessDesc: '',
  illnessTime: 0,
  consultFlag: undefined,
  pictures: []
})
const fileList = ref([]) // 上传的文件列表
// 文件类型判断
// 上传图片的格式  ['image/jpeg', 'image/gif', 'image/bmp', 'image/png', 'image/webp']
// 上传图片
// 'image/webp'
const beforeRead: UploaderBeforeRead = (file: File | File[]) => {
  // 进行类型判断，分为文件数组和单个文件的判断
  let formatFlag = true
  if (file instanceof Array) {
    file.forEach((item) => {
      if (!imageTypes.includes(item.type)) {
        showFailToast('上传图片的格式只能为jpeg,gif,bmp,png,webp')
        formatFlag = false
        // return false
      }
    })
    if (!formatFlag) return false
  } else {
    if (!imageTypes.includes(file.type)) {
      showFailToast('上传图片的格式只能为jpeg,gif,bmp,png,webp')
      return false
    }
  }
  // 校验成功
  return true
}
// 上传文件  => 数组和单个文件的统一添加
const upload = async (file: UploaderFileListItem) => {
  file.status = 'uploading'
  file.message = '上传中...'
  try {
    const { data } = await uploadImageAPI(file.file as File)
    file.status = 'done'
    file.message = '上传成功'
    file.url = data.url
    // 成功之后需要将当前的图片的地址存到FormData对象中的picture
    formData.value.pictures?.push(data)
  } catch (error) {
    file.status = 'failed'
    file.message = '上传失败'
  }
}
// 文件读取完成后的回调函数
const afetrRead: UploaderAfterRead = (
  item: UploaderFileListItem | UploaderFileListItem[]
) => {
  // 上传图片
  // 文件数组和单个文件上传方式不一样
  if (Array.isArray(item)) {
    // 每个文件需要遍历上传
    item.forEach((file) => {
      // 如果每一项中没有file，则需要直接return
      if (!file.file) return
      // 设置上传状态
      upload(file)
    })
  } else {
    if (!item.file) return
    upload(item)
  }
}
// 删除文件
const deleteFile = (item: UploaderFileListItem) => {
  // 需要将form中的相对应的图片进行删除
  formData.value.pictures = formData.value.pictures?.filter(
    (file) => file.url !== item.url
  )
}
// 设置下一步按钮的禁用标志
const flag = computed(() => {
  return formData.value.illnessDesc === '' ||
    formData.value.consultFlag === undefined ||
    formData.value.illnessTime === undefined
    ? true
    : false
})
// 点击下一步，保存数据到pinia中
const store = useConsultStore()
// ??? 为什么放在外面就可以？？？ => 编译的问题
const router = useRouter()
const submitForm = () => {
  // 拦截条件
  if (!formData.value.illnessDesc) return showToast('请输入症状详情')
  if (formData.value.illnessTime === undefined)
    return showToast('请选择患病时长')
  if (formData.value.consultFlag === undefined)
    return showToast('请选择是否就诊')
  store.setIllnessDesc(formData.value)
  // 跳转到家庭档案
  router.push({ name: 'patient', query: { isChange: 1 } })
}
// 当从家庭档案中回退到该页面之后，需要进行数据回显，获取上一个页面回到该组件时进行回显
onMounted(() => {
  // 从pinia中获取数据，判断是否存在有该页面所需要的数据
  if (store.consultInfo.illnessDesc) {
    // 显示模态框
    showConfirmDialog({
      title: '温馨提示',
      message: '是否恢复您之前填写的病情信息呢？'
    })
      .then(() => {
        const { illnessDesc, illnessTime, consultFlag, pictures } =
          store.consultInfo
        formData.value.illnessDesc = illnessDesc
        formData.value.illnessTime = illnessTime
        formData.value.consultFlag = consultFlag
        formData.value.pictures = pictures
      })
      .catch()
  }
})
</script>

<template>
  <div class="illness-consult-page">
    <DP-NavBar
      title="图文问诊"
      :back="
        () => {
          $router.replace({ name: 'DepConsult' })
        }
      "
    ></DP-NavBar>
    <div class="consult-form">
      <div class="form-head">
        <div class="left">
          <img class="avatar" src="@/assets/avatar-doctor.svg" alt="" />
        </div>
        <div class="right">
          <p class="title">在线医生</p>
          <p class="tip">
            请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助
          </p>
          <div class="safe">
            <DP-Icon name="consult-safe"></DP-Icon>
            <span>内容仅医生可见</span>
          </div>
        </div>
      </div>
      <div class="form-body">
        <van-field
          v-model="formData.illnessDesc"
          class="desc"
          rows="3"
          autosize
          type="textarea"
          placeholder="请详细描述您的病情，病情描述不能为空"
          show-word-limit
          :border="false"
        />
        <div class="item">
          <p>本次患病多久了？</p>
          <DP-radio-btn
            :options="timeOptions"
            v-model="formData.illnessTime"
          ></DP-radio-btn>
        </div>
        <div class="item">
          <p>此次病情是否去医院就诊过？</p>
          <DP-radio-btn
            :options="illnessedOptions"
            v-model="formData.consultFlag"
          ></DP-radio-btn>
        </div>
        <div class="item-img">
          <van-uploader
            v-model="fileList"
            upload-text="上传文件"
            upload-icon="photo-o"
            max-count="9"
            multiple
            :before-read="beforeRead"
            :after-read="afetrRead"
            max-size="5*1024*1024"
            @delete="deleteFile"
          >
            <template #preview-delete>
              <DP-icon name="consult-delete" :size="20"></DP-icon>
            </template>
          </van-uploader>
          <p v-if="fileList.length === 0">
            上传内容仅医生可见,最多9张图,最大5MB
          </p>
        </div>
        <van-button
          type="primary"
          round
          block
          :class="{ disabled: flag }"
          @click="submitForm"
          >下一步</van-button
        >
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.illness-consult-page {
  margin-top: 46px;
  .consult-form {
    margin-top: 10px;
    .form-head {
      display: flex;
      padding: 15px;
      border: 1px solid #f5f6f8;
      .left {
        .avatar {
          width: 52px;
          height: 52px;
          margin-top: 10px;
        }
      }
      .right {
        flex: 1;
        padding-left: 12px;
        .title {
          font-size: 15px;
          color: var(--cp-text1);
        }
        .tip {
          margin: 7px 0;
          font-size: 13px;
          color: var(--cp-text3);
          background-color: var(--cp-bg);
          padding: 12px;
          border-radius: 5px;
        }
        .safe {
          display: flex;
          align-items: center;
          font-size: 12px;
          color: var(--cp-text3);
          span {
            margin-left: 3px;
          }
        }
      }
    }
    .form-body {
      padding: 15px;
      .desc {
        padding: 0;
      }
      .item {
        p {
          padding: 15px 0;
        }
      }
      .item-img {
        display: flex;
        margin-top: 10px;
        align-items: center;
        font-size: 12px;
        color: var(--cp-tip);
        margin-bottom: 40px;
        ::v-deep() {
          .van-uploader__upload {
            border-radius: 8px;
            &-icon,
            &-text {
              color: var(--cp-text3);
            }
          }
          .van-uploader__preview {
            .van-image {
              .van-image__img {
                border-radius: 8px;
              }
            }
            &-delete {
              left: -10px;
              top: -10px;
            }
          }
        }
      }
      .van-button {
        font-size: 16px;
      }
      .disabled {
        background-color: #fafafa;
        color: #dedbde;
        border: #fafafa;
        opacity: 1;
      }
    }
  }
}
</style>
